import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '@/components/Home';
import Login from '@/components/Login';
import { Message } from 'element-ui';
import store from '../store';

Vue.use(VueRouter);

const router = new VueRouter({
  mode: 'history',
  //二级域名
  base: '/attendant_web',
  // base: process.env.BASE_URL,
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
    },
    {
      path: '/',
      name: 'home',
      component: Home,
      redirect: '/phone',
      children: [
        {
          path: '/phone',
          name: 'phone',
          component: () => import('@/components/Phone'),
        },
        {
          path: '/gis',
          name: 'gis',
          component: () => import('@/components/Gis'),
          meta: {
            keepAlive: true, // 需要被缓存
          },
        },
        {
          path: '/meeting',
          name: 'meeting',
          component: () => import('@/components/Meeting'),
          meta: {
            keepAlive: true, // 需要被缓存
          },
        },
      ],
    },
  ],
});

const LOGIN_PAGE_NAME = 'login';
const homeName = 'home';

router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('tokenSign');
  if (token) {
    store.commit('SetOperatorInfo');
  }

  // 未登录且要跳转的页面不是登录页
  if (to.name !== LOGIN_PAGE_NAME && !token) {
    // 跳转到登录页
    next({ name: LOGIN_PAGE_NAME });
    // 未登陆且要跳转的页面是登录页
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 跳转
    next();
    // 已登录且要跳转的页面是登录页
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    next({
      name: homeName, // 跳转到homeName页
    });
    // router.go(-1)
    // next(from.path)
    // next(false)
  } else {
    next();
  }
});

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

/**
 * 单模块跳转（无需登录）
 */
export function singleSignOn(to, next) {
  // http://localhost:7777/singleSignOn?path=myevent&type=idispatch
  //http://localhost:7777/singleSignOn?path=warning&type=idispatch
  console.log(to.query);
  //参数userName,password,path
  const data = to.query;
  //记录允许访问模块
  sessionStorage.setItem('allowPath', '/' + data.path);
  sessionStorage.setItem('loginType', data.type);
  next({ name: data.path });
  router.push({ name: data.path });
}

export default router;
